package com.demo.ocr;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import java.io.File;

/**
 * TODO OCR 识别
 * @author: 李德才
 * @description:
 * @create: 2021-06-05 16:04
 **/
public class OcrImageTest {

  private static final String TESS_DATA = "D:\\learn\\jfinal-demo\\target\\classes\\tessdata";
  private static final String IMAGE = "D:\\learn\\jfinal-demo\\src\\main\\resources\\image\\new.png";


  public static void main(String[] args) {
//    pomTest();
//    System.err.println("--------------------------------------------------------");
    exeTest();
  }


  /**
   * 使用Pom 依赖识别图像
   * @return void
   * @author 李德才
   * @date 2021/7/14 10:11
   */
  public static void pomTest() {
    ITesseract instance = new Tesseract();
    // 指定训练数据集合的路径
    instance.setDatapath(TESS_DATA);
    // 指定为中文识别
    instance.setLanguage("chi_sim");
    // 指定识别图片
    File imgDir = new File(IMAGE);
    long startTime = System.currentTimeMillis();
    String ocrResult = null;
    try {
      ocrResult = instance.doOCR(imgDir);
    } catch (TesseractException e) {
      e.printStackTrace();
    }
    // 输出识别结果
    System.out.println(
        "OCR Result: \n" + ocrResult + "\n 耗时：" + (System.currentTimeMillis() - startTime) + "ms");
  }


  /**
   * 使用应用程序识别图像
   * @return void
   * @author 李德才
   * @date 2021/7/14 10:11
   */
  public static void exeTest() {
    BufferedReader br = null;
    try {

      List<String> cmdList = new ArrayList<>();
//      应用文件位置
      cmdList.add("D:\\OCR\\tesseract-ocr\\tesseract ");
//      图像位置
      cmdList.add("D:\\learn\\jfinal-demo\\src\\main\\resources\\image\\new.png ");
//      生成的文件位置
      cmdList.add("D:\\learn\\jfinal-demo\\src\\main\\resources\\image ");
//      其余参数
      cmdList.add(" --oem 1 -l chi_sim ");
      StringBuilder builder = new StringBuilder();
      cmdList.forEach(builder::append);
      System.err.println(builder);
      Process process = Runtime.getRuntime().exec(builder.toString());
      br = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String line = null;
      while ((line = br.readLine()) != null) {
        System.out.println(line);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {

      if (br != null) {
        try {
          br.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
}
